package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.ihomey.cc.library.toprightmenu.MenuItem;
import com.ihomey.cc.library.toprightmenu.TopRightMenu;
import com.ihomey.cc.library.util.DensityUtil;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.app.Constant;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.controller.Controller;
import com.ihomey.linkuphome.controller.ControllerFactory;
import com.ihomey.linkuphome.entities.Device;
import com.ihomey.linkuphome.entities.LightState;
import com.ihomey.linkuphome.listeners.BatteryListener;
import com.ihomey.linkuphome.util.AnimationUtil;
import com.ihomey.linkuphome.util.BindView;
import com.ihomey.linkuphome.widget.RGBCircleView;
import com.ihomey.linkuphome.widget.SingleSelectToggleGroup;
import com.ihomey.linkuphome.widget.ToggleButtonGroup;

import static com.ihomey.linkuphome.entities.Device.DEVICE_ADDR_BASE;
import static com.ihomey.linkuphome.entities.Device.DEVICE_ID_UNKNOWN;

/**
 * Created by Administrator on 2017/4/20.
 */

public class ControlFragment extends BaseFragment implements View.OnClickListener, BatteryListener {

    private static final String DEVICE_LAST_ID = "lastDeviceID";

    @BindView(id = R.id.iv_battery)
    private ImageView iv_battery;
    @BindView(id = R.id.tv_name)
    private TextView tv_name;
    @BindView(id = R.id.rcv)
    private RGBCircleView rgbCircleView;
    @BindView(id = R.id.seekbar_light)
    private SeekBar lightSeekBar;
    @BindView(id = R.id.single_selection_speed)
    private SingleSelectToggleGroup singleSelectToggleGroup;
    @BindView(id = R.id.checkbox_switch_color)
    private CheckBox checkbox_switch_color;
    @BindView(id = R.id.checkbox_switch_mode)
    private CheckBox checkbox_switch_mode;
    @BindView(id = R.id.checkbox_switch_power)
    private CheckBox checkbox_switch_power;
    @BindView(id = R.id.checkbox_switch_scene)
    private CheckBox checkbox_switch_scene;

    private MainActivity mainActivity;
    private Device selectedDevice;
    private TopRightMenu mTopRightMenu;
    private LightState lightState = null;
    private DeviceController mController;
    private Controller controller;
    private double groupBatteryLevel = -1;
    private boolean isRecovering=false;
    private final int[] batteryIcons = {R.drawable.ic_battery0, R.drawable.ic_battery1, R.drawable.ic_battery2, R.drawable.ic_battery3, R.drawable.ic_battery4, R.drawable.ic_battery5, R.drawable.ic_battery6};

    public static ControlFragment newInstance(int lightType) {
        ControlFragment fragment = new ControlFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("lightType", lightType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_control, null);
        if (mController.getDeviceType() == 1) {
            ((ViewStub) view.findViewById(R.id.include_control_lawn_header)).inflate();
            ((ViewStub) view.findViewById(R.id.include_control_lawn)).inflate();
        } else if (mController.getDeviceType() == 2) {
            ((ViewStub) view.findViewById(R.id.include_control_rgb_header)).inflate();
            ((ViewStub) view.findViewById(R.id.include_control_rgb)).inflate();
        }
        controller = new ControllerFactory().createController(mController.getDeviceType());
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }



    @Override
    public void initWidget(View parentView) {
        initTopRightMenu();
        mainActivity.getRightTv().setOnClickListener(this);
        lightSeekBar.setMax(84);
        lightSeekBar.setOnSeekBarChangeListener(brightChange);
        rgbCircleView.setCircleTimerListener(circleColorChange);
        checkbox_switch_color.setOnCheckedChangeListener(colorChange);
        checkbox_switch_mode.setOnCheckedChangeListener(modeChange);
        checkbox_switch_power.setOnCheckedChangeListener(powerChange);
        if (checkbox_switch_scene != null) {
            checkbox_switch_scene.setOnClickListener(sceneChange);
        }
        singleSelectToggleGroup.setOnCheckedChangeListener(speedChange);
    }

    @Override
    public void onResume() {
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.showRightBtn(true);
        mainActivity.setTitle(R.string.tab_control);
        setUpLightStateView();
        super.onResume();
    }

    public void setUpLightStateView() {
        if (mController.getSelectedDeviceId() == Device.DEVICE_ID_UNKNOWN) {
            int lastDeviceIdUsed = getActivity().getSharedPreferences("ihomey", Activity.MODE_PRIVATE).getInt(DEVICE_LAST_ID + mController.getDeviceType(), Device.DEVICE_ID_UNKNOWN);
            if (lastDeviceIdUsed != Device.DEVICE_ID_UNKNOWN) {
                mController.setSelectedDeviceId(lastDeviceIdUsed);
            }
        }
        selectedDevice = mController.getDevice(mController.getSelectedDeviceId(), mController.getSelectedDeviceId() > DEVICE_ADDR_BASE ? 0 : 1);
        if (selectedDevice != null) {
            if(mController.getDeviceType()==1){
                Log.d("aa","getBatteryState:"+selectedDevice.getDeviceId());
                mController.getBatteryState(selectedDevice.getDeviceId(), this);
            }
            tv_name.setText(selectedDevice.getName());
        } else {
            if(mController.getDeviceType()==1){
                iv_battery.setVisibility(View.INVISIBLE);
            }
            tv_name.setText(null);
        }
        lightState = mController.getLightState(mController.getSelectedDeviceId());
        if (lightState != null) {
            isRecovering=true;
            lightSeekBar.setProgress(lightState.getBrightness());
            checkbox_switch_power.setChecked(lightState.getIsOn() == 1 ? true : false);
            checkbox_switch_mode.setChecked(lightState.getIsLight() == 1 ? true : false);
            rgbCircleView.setIndex(lightState.getColorPosition());
            if (lightState.getChangeMode() != -1) {
                checkbox_switch_color.setChecked(true);
            } else {
                checkbox_switch_color.setChecked(false);
            }
            isRecovering=false;
        }

    }

    public void storeLightState() {
        groupBatteryLevel = -1;
        lightState = mController.getLightState(mController.getSelectedDeviceId());
        if (lightState != null) {
            lightState.setIsOn(checkbox_switch_power.isChecked() ? 1 : 0);
            lightState.setIsLight(checkbox_switch_mode.isChecked() ? 1 : 0);
            lightState.setBrightness(lightSeekBar.getProgress());
            lightState.setChangeMode(singleSelectToggleGroup.getVisibility() == View.VISIBLE ? singleSelectToggleGroup.getCheckedPosition() : -1);
            lightState.setColorPosition(rgbCircleView.getCurrentIndex());
            mController.updateDeviceLightState(lightState);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        storeLightState();
    }

    protected RGBCircleView.CircleTimerListener circleColorChange = new RGBCircleView.CircleTimerListener() {
        @Override
        public void onTimerSetValueChanged(final int position) {
            checkbox_switch_color.setChecked(false);
            checkbox_switch_mode.setChecked(false);
            if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        String colorValue = Constant.CODE_LIGHT_COLORS[position];
                        controller.setLightColor(mController.getSelectedDeviceId(), colorValue);
                    }
                }, 300);
            }
        }

        @Override
        public void onTimerSetValueChange(final int position) {
            checkbox_switch_color.setChecked(false);
            checkbox_switch_mode.setChecked(false);
            if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        String colorValue = Constant.CODE_LIGHT_COLORS[position];
                        controller.setLightColor(mController.getSelectedDeviceId(), colorValue);
                    }
                }, 300);
            }
        }
    };

    protected SeekBar.OnSeekBarChangeListener brightChange = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                int currentProgress = seekBar.getProgress() + 15;
                controller.setLightBright(mController.getSelectedDeviceId(), currentProgress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    protected CompoundButton.OnCheckedChangeListener colorChange = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isChecked) {
                singleSelectToggleGroup.setVisibility(View.INVISIBLE);
                singleSelectToggleGroup.setAnimation(AnimationUtil.moveToViewBottom());
            } else {
                checkbox_switch_mode.setChecked(false);
                singleSelectToggleGroup.setVisibility(View.VISIBLE);
                singleSelectToggleGroup.setAnimation(AnimationUtil.moveToViewLocation());
                if (lightState != null && lightState.getChangeMode() != -1) {
                    singleSelectToggleGroup.setCheckedAt(lightState.getChangeMode(), true);
                    if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                        controller.setLightSpeed(mController.getSelectedDeviceId(), lightState.getChangeMode());
                    }
                } else {
                    singleSelectToggleGroup.setCheckedAt(1, true);
                    if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                        controller.setLightSpeed(mController.getSelectedDeviceId(), 1);
                    }
                }
            }
        }
    };

    protected ToggleButtonGroup.OnCheckedChangeListener speedChange = new ToggleButtonGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChange(int position, boolean isChecked) {
            if (!isRecovering&&isChecked && mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                controller.setLightSpeed(mController.getSelectedDeviceId(), position);
            }
        }
    };

    protected CompoundButton.OnCheckedChangeListener modeChange = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isRecovering&&isChecked && mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                checkbox_switch_color.setChecked(false);
                controller.setLightingMode(mController.getSelectedDeviceId());
            } else if (!checkbox_switch_color.isChecked() && mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                rgbCircleView.setIndex(rgbCircleView.getCurrentIndex());
                if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            String colorValue = Constant.CODE_LIGHT_COLORS[rgbCircleView.getCurrentIndex()];
                            controller.setLightColor(mController.getSelectedDeviceId(), colorValue);
                        }
                    }, 300);
                }
            }
        }
    };

    protected View.OnClickListener sceneChange = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((ControlParentFragment) getParentFragment()).showFragment(SceneSettingFragment.newInstance());
        }
    };

    protected CompoundButton.OnCheckedChangeListener powerChange = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isRecovering&&mController.getSelectedDeviceId() != Device.DEVICE_ID_UNKNOWN) {
                controller.setLightPowerState(mController.getSelectedDeviceId(), isChecked ? 1 : 0);
            }
        }
    };

    private void initTopRightMenu() {
        mTopRightMenu = new TopRightMenu(getActivity());
        mTopRightMenu.setWidth(DensityUtil.getScreenW(getActivity()) * 5 / 12);
        mTopRightMenu.showIcon(true).dimBackground(false).needAnimationStyle(true).setAnimationStyle(R.style.TRM_ANIM_STYLE).addMenuItem(new MenuItem(R.drawable.ic_rename, R.string.rename));
        if (mController.getDeviceType() == 2) {
            mTopRightMenu.addMenuItem(new MenuItem(R.drawable.ic_alarm, R.string.timer));
        }
        mTopRightMenu.addMenuItem(new MenuItem(R.drawable.ic_scan, R.string.scan)).addMenuItem(new MenuItem(R.drawable.ic_share, R.string.shareOperation)).setOnMenuItemClickListener(topRightMenuItemClickListener);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_right) {
            int xOffSet = DensityUtil.getScreenW(getActivity()) * 5 / 12 - DensityUtil.dip2px(getActivity(), 22) - view.getWidth() / 2;
            mTopRightMenu.showAsDropDown(view, -xOffSet, DensityUtil.dip2px(getActivity(), 11));
        }
    }


    protected TopRightMenu.OnMenuItemClickListener topRightMenuItemClickListener = new TopRightMenu.OnMenuItemClickListener() {
        @Override
        public void onMenuItemClick(int position, int itemId) {
            switch (itemId) {
                case R.drawable.ic_rename:
                    if (mController.getSelectedDeviceId() != 0) {
                        final Device selectDevice = mController.getDevice(mController.getSelectedDeviceId());
                        if (selectDevice != null) {
                            new MaterialDialog.Builder(getActivity()).title(R.string.rename).inputType(InputType.TYPE_CLASS_TEXT |
                                    InputType.TYPE_TEXT_FLAG_CAP_WORDS)
                                    .inputRange(2, 24)
                                    .positiveText(R.string.confirm)
                                    .input(selectDevice.getName(), selectDevice.getName(), false, new MaterialDialog.InputCallback() {
                                        @Override
                                        public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                            if (!TextUtils.equals(selectDevice.getName(), input.toString())) {
                                                mController.updateDeviceName(selectDevice.getDeviceId(), input.toString());
                                                tv_name.setText(input.toString());
                                            }
                                        }
                                    }).show();
                        }
                    }
                    break;
                case R.drawable.ic_alarm:
                    ((ControlParentFragment) getParentFragment()).showFragment(TimerSettingFragment.newInstance());
                    break;
                case R.drawable.ic_scan:
                    mainActivity.showFragment(ScanFragment.newInstance());
                    break;
                case R.drawable.ic_share:
                    mainActivity.showFragment(ControlShareFragment.newInstance());
                    break;
            }
        }
    };

    @Override
    public void onBatteryLevelReceived(int deviceId, double batteryValue) {
        if (DEVICE_ID_UNKNOWN != deviceId&&DEVICE_ADDR_BASE != deviceId) {
            Log.d("aa","onBatteryLevelReceived:"+batteryValue);
            if (mController.getSelectedDeviceId() < DEVICE_ADDR_BASE) {
                if (groupBatteryLevel == -1) {
                    groupBatteryLevel = batteryValue;
                } else if (batteryValue < groupBatteryLevel) {
                    groupBatteryLevel = batteryValue;
                }
                setBatteryLevel((int)Math.ceil(groupBatteryLevel/20.0));
            } else if(deviceId==mController.getSelectedDeviceId()){
                setBatteryLevel((int)Math.ceil(batteryValue/20.0));
            }
        } else {
            iv_battery.setVisibility(View.GONE);
        }
    }

    private void setBatteryLevel(int level) {
        iv_battery.setVisibility(View.VISIBLE);
        iv_battery.setImageResource(batteryIcons[level]);
    }
}
